package com.hhq.usercenter.security;

import cn.hutool.core.util.URLUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;


/**
 * <p>Description: 动态权限数据源，用于获取动态权限规则 </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/1/9 18:29
 */
@Component
@Slf4j
public class DynamicSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static Map<String, ConfigAttribute> configAttributeMap = null;
    @Autowired
    private DynamicSecurityService dynamicSecurityService;

    @PostConstruct
    public void loadDataSource() {
        try {
            configAttributeMap = dynamicSecurityService.loadResourceSource();
        } catch (Exception e) {
            log.error("loadDataSource error", e);
        }
    }

    public void clearDataSource() {
        configAttributeMap.clear();
        configAttributeMap = null;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //查看配置信息的map是否有信息
        if (configAttributeMap == null) {
            this.loadDataSource();
        }
        List<ConfigAttribute> configAttributes = new ArrayList<>();
        //获取当前请求的url
        String url = ((FilterInvocation) object).getRequestUrl();
        //从url中提取路径
        String path = URLUtil.getPath(url);
        //创建一个路径匹配对象
        PathMatcher pathMatcher = new AntPathMatcher();
        //configAttributeMap的所有键（这些键是路径模式）的迭代器
        //获取到访问资源
        for (String patten : configAttributeMap.keySet()) {
            if (pathMatcher.match(patten, path)) {
                configAttributes.add(configAttributeMap.get(patten));
            }
        }
        return configAttributes;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
